package command
{
	import com.adobe.cairngorm.commands.Command;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import event.LoginRequest;
	
	import model.Model;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import services.databasewrapper.DatabaseWrapper;
	
	import valueObjects.VOUser;
	
	public class RegisterCommand implements IResponder, Command
	{
		/**
		 * 	model
		 */ 
		public var tripModel : Model = Model.instance;
		
		public var username:String;
		public var password:String;
		
		
		public function RegisterCommand()
		{
		}
		
		public function execute(e:CairngormEvent):void
		{
			trace ("Login request...");
			var databaseWrapper:DatabaseWrapper = new DatabaseWrapper();
			databaseWrapper.addEventListener(FaultEvent.FAULT, fault);
			databaseWrapper.addEventListener(ResultEvent.RESULT, result);			
			databaseWrapper.register((e as LoginRequest).additionalData.user);
			
			username = ((e as LoginRequest).additionalData.user as VOUser).username;
			password = ((e as LoginRequest).additionalData.user as VOUser).password;
			
		}
		
		public function result(data:Object):void
		{
			if ( data.result)
			{
				var loginEvent:LoginRequest = new LoginRequest(LoginRequest.LOGIN);
				loginEvent.additionalData.username = username;
				loginEvent.additionalData.password = password;
				loginEvent.dispatch();
			}
			else
			{
				Alert.show("That username already exist in the database");
			}
			
		}
		
		public function fault(info:Object):void
		{
			Alert.show("Registration was unsuccessful");
		}
		
	}
}